<template>
   <section id="ex-page">
      <article class="top">
        <p class="time">倒计时：{{lastTime}}s</p>
        <p class="user-img">
          <img class="userImg" :src='HeadImg'/>
        </p>
      </article>
      <w-row direction="column" align="center">
        <w-cell>
            <article class="center">
                <p class="ex-body">
                  {{this.exDetail.Title}}
                </p>
            </article>
            <article class="bottom">
              <w-cell align="center">
                  <!--:class="{ selected :initBg == 0 }"-->
                  <w-button border-color="#dbd9d9" width="18rem" height="2rem" class="init"  v-for="(val,key,index) in JSON.parse(this.exDetail.Option)" :key="index"  @click="change(index,key)">{{val}}</w-button>
              </w-cell>
            </article>
        </w-cell>
      </w-row>
   </section>
</template>

<script>
    import Vue from 'vue'
    import { mapGetters, mapActions } from 'vuex';
    import axios from 'axios'
    //import axiosFetch from '../../fetch/axios'
    let user;
    let interval;
    export default {
        name: "ex",
        data() {
          return {
             exData: [],
            //   exData: [
            //       {
            //           Title: "有一块天然的黑色的大理石，在九月七号这一天，把它扔到钱塘江里会有什么现象发生11？",
            //           Options: {"A": "朴在水上1","B": "飞在空中1","C": "沉到江底1"},
            //           TrueAsk: 'B'
            //       },
            //        {
            //           Title: "有一块天然的黑色的大理石，在九月七号这一天，把它扔到钱塘江里会有什么现象发生22？",
            //           Options: {"A": "朴在水上2","B": "飞在空中2","C": "沉到江底2"},
            //           TrueAsk: 'A'
            //       },
            //        {
            //           Title: "有一块天然的黑色的大理石，在九月七号这一天，把它扔到钱塘江里会有什么现象发生33？",
            //           Options: {"A": "朴在水上3","B": "飞在空中3","C": "沉到江底3"},
            //           TrueAsk: 'C'
            //       },
            //        {
            //           Title: "有一块天然的黑色的大理石，在九月七号这一天，把它扔到钱塘江里会有什么现象发生44？",
            //           Options: {"A": "朴在水上4","B": "飞在空中4","C": "沉到江底4","D": "沉到江底4"},
            //           TrueAsk: 'D'
            //       }
            //   ],
              initBg: -1,
              exIndex: 0,
              sources: 0,
              exDetail: { 
                  Option: {
                  }
              },
              lastTime: 10,
              isLoading: false,

              HeadImg: ''
          }
        },
        computed: {
            ...mapGetters({
                exList: 'exList'
            })
        },
        mounted() {
//   if(localStorage.openID == "" || localStorage.openID == undefined || localStorage.openID == "undefined") {
//                  axios.get('/wx/getcodeurl', {　
//                     params: { 'Appid': 'wx27a54ca734af2cf8','redirect_uri': 'http://zqdn.aegis-s.com/wx/getwxusertoex' }
//                       }).then(function(response) {
//                         //引导用户根据地址获取code
//                         //location.href= response.data;
//                         let wxobj = this.GetRequest(response.data);
//                         let openid = wxobj["/ex?openid"];
//                         localStorage.openID = openid;
//                         location.reload();
//                       }).catch(function(error) {　　
//                         console.log(error);　
//                 });
//             } else {
            //let openid = "oGqC5jgtFzCVXPrTQafjapEzX1iI";
             let wxobj = this.GetRequest(location.hash);
             let openid = wxobj["/ex?openid"];
             localStorage.openID = openid;

            this.checkUserInfo(openid).then((res)=> {
                let _res = res[0];
                if(_res.msg == '0') { 
                    Wui.Toast.show('尚未注册，请先注册', 'middle');
                    setTimeout(function() {
                        location.href = '#/registtpl';
                    }, 1000);
                  
                  } else if(_res.msg == '1') {
                    
                    //  查看今天答了几次题
                    this.getTodayTimes(openid).then((res)=>{
                            let _data = res.data;
                            // alert("您今天已累计答题："+_data.todayCount+"次");
                            if(_data.Result=="success"){
                                if(_data.todayCount>2){
                                    Wui.Toast.show('每人每天只能答题3次，请您明天再来', 'middle');
                                    setTimeout(function() {
                                        Vue.prototype.$wx.closeWindow();
                                    }, 1000);
                                }
                            }
                    });

                    this.getExList().then((res) => {
                        this.exData = res.data;
                        this.HeadImg = _res.userInfo.HeadImg;
                        var _user = JSON.stringify(_res.userInfo);
                        localStorage.setItem('userMsg',_user);
                                
                        this.exDetail = this.exData[0];
                        let me = this;
                        interval = window.setInterval(function() {
                            me.lastTime--;
                            if(me.lastTime <= 0) {
                                window.clearInterval(interval);
                                me.$router.push({name:'result',params: {openid: localStorage.openID}});
                            }
                        }, 1000);
                    });
                } else {
                     Wui.Toast.show(_res.msg, 'middle');
                }
            });

            //}
        },
        methods: {
           ...mapActions([
            'update',
            'getUserInfo',
            'checkUserInfo',
            'getExList',
            'addExLog',
            'getTodayTimes'
           ]),
           change(index,key) {  
             let me = this;
             this.lastTime = 10;
             this.initBg = index;
             let EID = this.exDetail.ID;
             this.exIndex = this.exIndex + 1; 


             if(this.exIndex >= this.exData.length) {
                 this.exDetail = this.exData[this.exData.length-1];
             } else {
                 this.exDetail = this.exData[this.exIndex];
             }
             if(this.exData[this.exIndex-1].TureOption == key) {
                 //this.sources = this.sources + 20; //积分
             } else {

                 let tempExpar = {
                       openID: localStorage.openID,
                       EID: EID,
                       Answer: key,
                       isTrue: (this.exData[this.exIndex-1].TureOption == key ? true : false),
                       Type: 2
                   }
                   this.addExLog(tempExpar).then((res) => {
                        console.log("答题记录保存");
                        localStorage.removeItem("userMsg");
                        var _user = JSON.stringify(res.userInfo)
                        localStorage.setItem('userMsg',_user);
                        if(this.exIndex >= this.exData.length) {
                          me.$router.push({name:'result',params: {openid: localStorage.openID}});
                        }
                   });


                 window.Wui.Toast.show("挑战失败", 'middle'); 
                 setTimeout(function() {
                      me.$router.push({name:'result',params: {openid: localStorage.openID}});
                      
                 }, 1500);
                 window.clearInterval(interval);
                 return false;
             }
            
             //if(this.exIndex > this.exData.length-1) {
                 //更新用户积分
                // let params = {
                //     Integral: 2,//this.sources, 每题20分
                //     openID: localStorage.openID
                // }
                // this.update(params).then((res) => {
                //   if(res.Result == 'success') {
                //         localStorage.removeItem("userMsg");
                //         var _user = JSON.stringify(res.userInfo)
                //         localStorage.setItem('userMsg',_user);
                //         //window.clearInterval(interval);
                //         if(this.exIndex >= this.exData.length) {
                //           me.$router.push({name:'result',params: {openid: localStorage.openID}});
                //         }
                   //添加答题记录
                   let expar = {
                       openID: localStorage.openID,
                       EID: EID,
                       Answer: key,
                       isTrue: (this.exData[this.exIndex-1].TureOption == key ? true : false),
                       Type: 2
                   }
                   this.addExLog(expar).then((res) => {
                        console.log("答题记录保存");
                        localStorage.removeItem("userMsg");
                        var _user = JSON.stringify(res.userInfo)
                        localStorage.setItem('userMsg',_user);
                        if(this.exIndex >= this.exData.length) {
                          me.$router.push({name:'result',params: {openid: localStorage.openID}});
                        }
                   });
                //   }
                // });
                 if(this.exIndex >= this.exData.length) {
                    window.Wui.Toast.show("挑战成功", 'middle'); 
                    let openid = localStorage.openID;
                    setTimeout(function() {
                        me.$router.push({name:'result',params: {openid: localStorage.openID}});
                    }, 1500);
                    window.clearInterval(interval);
                    this.exIndex = 0;
                    return false;
                 }
             //} 
           },
           GetRequest: function(url) {
            var url = decodeURI(url); //获取url中"?"符后的字串   
            var theRequest = {};
            if (url.indexOf("?") != -1) {   
                var str = url.substr(1);   
                let strs = str.split("&");   
                for(var i = 0; i < strs.length; i ++) {   
                    theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);   
                }   
            }  
            return theRequest;   
          }  
        }
    }
    //  window.addEventListener("popstate", function(e) {  //回调函数中实现需要的功能
    //     Vue.prototype.$wx.closeWindow();
    //  }, false);  
</script>

<style lang="scss" scoped>
  #ex-page {
      font-size: 0.8rem;
      .top {
          width: 100%;
          height: 3.5rem;
          background: #005ba8;
          position: relative;
          text-align: center;
          .time {
              margin: 0;
              padding: 0;
              color: #fff;
              line-height: 3.5rem;
          }
          .user-img {
                 position: absolute;
                 top: 0.6rem;
                 left: 1rem;
               img {
                   width: 3.7rem;
               }
          }
      }
      .center {
          width: 88%;
          margin: 3rem auto;
          .ex-body {
              color: #005ba8;
              line-height: 1.5rem;
          }
      }
      .bottom {
          width: 88%;
          margin: 0 auto;
          .wui-button {
              margin-top: 1.3rem !important;
          }
      }
    .init {
        background: #f2f2f2;
        color: #242424;
    }
    .selected {  
        background: #005ba8;
        color: #fff;
    }  
    .userImg {
        border-radius: 50px;
    }
  }
</style>